const { app, BrowserWindow,ipcMain  } = require('electron')
const electron = require('electron')
const fs = require('fs')
const os = require('os')
const { sep } = require('path')
const path = require("node:path");
const cp = require('child_process')

let useExternalPy = false;
let pythonExternalPath = 'python';//默认为python

//获取python的位置
function getPythonPath() {
    //获取优先使用外部数据判断
    if (useExternalPy === true){
        //不为空且不是false，即为真
        return pythonExternalPath;
    }
    if (os.platform() === 'win32'){
        //windows平台
        if (os.arch() === 'ia32'){
            //x86
            return path.join(__dirname,"resource/win/x86/python.exe");
        }else if (os.arch() === 'x64'){
            //x64
            return path.join(__dirname,"resource/win/x64/python.exe");
        }
    }else if (os.platform() === 'linux'){
        //Linux平台：从环境变量中获取python的位置
        return  "python";
    }else if (os.platform() === 'darwin'){
        //mac平台：从环境变量中获取python的位置
        return  "python";
    }
    //从内部存储读取
    return pythonExternalPath;
}

//本地调用Python程序
function runPython(code){
    //判断数据是否存在
    if (getPythonPath() === ''){
        electron.dialog.showErrorBox('错误','无外部Python可执行文件，请设置Python可执行文件路径，Linux和Mac用户请注意python环境的存在。')
        return console.error(err);
    }
    //创建临时文件
    let codeFileName = `${os.tmpdir()}${sep}py-${Date.now()}.py`;
    fs.writeFile(codeFileName,code,function (err) {
        if (err) {
            electron.dialog.showErrorBox('错误','写入代码到临时文件夹中失败，请确保使用管理员权限！')
            return console.error(err);
        }
        if (os.platform() === 'win32'){
            cp.exec(`start /w "${getPythonPath()}" ${codeFileName}`)
        }else {
            cp.exec(`${getPythonPath()} ${codeFileName}`)
        }
    });
}


//通信
const initializeIpcMain = () => {
    //run-python方法，传入code参数
    ipcMain.on('run-python', (event, code) => {
        const webContents = event.sender
        const win = BrowserWindow.fromWebContents(webContents)
        runPython(code)
    });
    ipcMain.on('set-use-external-py',(event, state) =>{
        useExternalPy = state;
    })
    ipcMain.on('set-py-external-path',(event, pyPath) =>{
        pythonExternalPath = pyPath;
    })
    //返回python的文件
    ipcMain.handle('dialog:openFile',async () => {
        const { canceled, filePaths } = await electron.dialog.showOpenDialog()
        if (!canceled) {
            return filePaths[0];
        }
    });
}

//创建一个窗口，引入preloadjs
const createWindow = (index_name,preloadJs='preload.js') => {
    //隐藏顶部菜单
    electron.Menu.setApplicationMenu(null)
    // Create the browser window.
    const mainWindow = new BrowserWindow({
        width: 1000,
        height: 800,
        icon: path.join(__dirname,'./static/img/logo/logo.png'),
        webPreferences: {
            preload: path.join(__dirname, preloadJs)
        }
    })
    // 加载 index.html
    mainWindow.loadFile(path.resolve(__dirname, index_name) )
    // 打开开发工具
    //mainWindow.webContents.openDevTools()
    return mainWindow
}

app.whenReady().then(() => {
    //创建一个窗口
    mainWindows = createWindow('index.html')
    initializeIpcMain() //初始化通信
    app.on('activate', () => {
        //点击托盘时创建一个窗口
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow('./index.html')
            initializeIpcMain() //初始化通信
        }
    })
})
//当所有窗口被关闭时，退出程序
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') app.quit()
})
